package web

import (
	"net/http"
	"strings"
	"path/filepath"
	"os"
)

// 视图接口
type ControllerInterface interface{
	Handler(response http.ResponseWriter, request *http.Request)
}

var (
	// 模板文件地址列表
	staticFilePath string = "web/src/"
	controllerMaps map[string]ControllerInterface = make(map[string]ControllerInterface)
)

var (
	// 静态文件服务列表
	staticFileMap	map[string]string = make(map[string]string)
)

//
// 设置静态文件目录
// url: URL请求路径
// 对应的静态文件路径
//
func setStaticPath(url string, path string) (ok bool) {
	ok = false

	if !strings.HasPrefix(url, "/") {
		url = "/" + url
	}

	err := filepath.Walk(path, func(p string, f os.FileInfo, err error) error {
		if f == nil {
			return err
		}

		if f.IsDir() {
			return nil
		}

		l := strings.TrimPrefix(p, path)
		if l == ""{
			return nil
		}

		staticFileMap[url+l] = p
		return nil
	})

	if err == nil {
		ok = true
	}

	return
}

//
// 静态文件服务
//
func serverStaticRouter(url string, response http.ResponseWriter, request *http.Request) (ok bool) {
	ok = false

	path, ok := staticFileMap[url]
	if !ok {
		return
	}

	http.ServeFile(response, request, path)

	ok = true
	return
}
